package online.foxnull2.foxmall.order.web;

import online.foxnull2.foxmall.order.exception.StockInsufficientException;
import online.foxnull2.foxmall.order.service.OrderService;
import online.foxnull2.foxmall.order.vo.orderConfirm.OrderConfirmVo;
import online.foxnull2.foxmall.order.vo.orderSubmitResp.OrderSubmitRespVo;
import online.foxnull2.foxmall.order.vo.orderSubmitResp.OrderSubmitVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class OrderWebController {

    private final OrderService orderService;

    @Autowired
    public OrderWebController(OrderService orderService) {
        this.orderService = orderService;
    }

    @GetMapping("/toTrade")
    public String toTrade(Model model) {

        OrderConfirmVo orderConfirmVo = orderService.confirmOrder();
        model.addAttribute("orderConfirmData", orderConfirmVo);
        return "confirm";
    }

    @PostMapping("/order/submit")
    public String orderSubmit(OrderSubmitVo orderSubmitVo,
                              Model model,
                              RedirectAttributes redirectAttributes) {
        String msg;
        try {
            OrderSubmitRespVo orderSubmitRespVo = orderService.orderSubmit(orderSubmitVo);
            if (orderSubmitRespVo.getCode() == 0) {
                model.addAttribute("orderSubmitRespVo", orderSubmitRespVo);
                return "pay";
            }
            switch (orderSubmitRespVo.getCode()) {
                case 1: {
                    msg = "token invalid";
                    break;
                }
                case 2: {
                    msg = "payAmount not equals payPrice";
                    break;
                }
                default: {
                    msg = "Order failed";
                }
            }
        } catch (StockInsufficientException e) {
            msg = "sku stock insufficient";
        }
        redirectAttributes.addFlashAttribute("msg", msg);
        return "redirect:http://order.foxmall.com/toTrade";
    }
}
